#pragma once
#include<iostream>
#include<queue>
#include<pthread.h>
#include<unistd.h>
template<class T>
class BlockQueue
{
public:
    BlockQueue(int maxcap = 5)
    :_maxcap(maxcap)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_c_cond,nullptr);
        pthread_cond_init(&_p_cond,nullptr);
        _low_water = _maxcap/3;
        _high_water = (_maxcap*2)/3;
    }
    T pop()
    {
        pthread_mutex_lock(&_mutex);
        while(_q.size() == 0)
        {
            pthread_cond_wait(&_c_cond, &_mutex);
        }
        T out = _q.front();
        _q.pop();
        if(_q.size() < _low_water)
            pthread_cond_signal(&_p_cond);
        pthread_mutex_unlock(&_mutex);
        return out;
    }
    void push(const T& t)
    {
        pthread_mutex_lock(&_mutex);
        while(_q.size() == _maxcap)
        {
            pthread_cond_wait(&_p_cond, &_mutex);
        }
        _q.push(t);
        if(_q.size() > _high_water)
            pthread_cond_signal(&_c_cond);
        pthread_mutex_unlock(&_mutex);
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }
private:
    std::queue<T> _q;
    int _maxcap;
    pthread_mutex_t _mutex;
    pthread_cond_t _c_cond;
    pthread_cond_t _p_cond;
    int _low_water;
    int _high_water;
};